# Main file that initiates and calls all the other functions.

# Steps:
# (1) Read in assembly file.
# (2) Make basic blocks.

from block import *

#clean the code from unuseful stuff
def clean_code(line):
	#removes all the comments
	line = line.replace(line[line.find("#"):line.find("\n")], "");
	#removes all the \n to make the code compact
	line = line.replace("\n","");
	#removes all the \t to make the code compact
	line = line.replace("\t"," ");
	return line

#recognize an instruction and split it into a list of elements like ['move','$regA,'$regB']
def instruction_split(line):
	line = filter(None, line.split(" "))
	for	elem in line:
		line2 = filter(None, elem.split(","))
		if len(line2)!=1:
			line.pop(line.index(elem))
			line = line + line2
	return line


def make_blocks(filename):
    all_blocks = []
    block_no = 0
    
    #read a file and put it into a list
    with open(filename) as f:
            content = f.readlines()
    f.close()
    #creates a new file for the optimization
    f = open("new"+filename, "w")
    bool = False
    for	i,line in enumerate(content):
        #clean the line from unuseful stuff
        line = clean_code(line)
        main = instruction_split(line)
##        print str(i)+") "+str(main)

        #until it didn't find the main just write what it is written
        if line.rstrip() and main[0] == "main:":
              bool = True

        #once he find the main start to create basic blocks.
        if line.rstrip() and bool==True:
            line = line.strip()
			
# --->>> check every line for these characters
            if (line[0:4] == 'main') or (line[0:2] == '$L') or (line[0] == 'b') or (line[0] == 'j'):
                all_blocks.append(Block(line[:-1]))
                block_no = block_no + 1
            else:
                all_blocks[block_no-1].add_instruction(line)
                
        print "len", len(all_blocks)
        
if __name__ == '__main__':
    filename = "simple-comp.annot.s"
    all_blocks = make_blocks(filename)
